package com.iwuke.dance.wxapi;


import android.app.Activity;
import android.os.Bundle;

import com.iwuke.dance.activity.LPWHApplication;
import com.iwuke.dance.http_request.PathUrl;
import com.iwuke.dance.util.LogUtil;
import com.iwuke.dance.util.SharedPreferencesUtil;
import com.iwuke.dance.util.ToastUtil;
import com.iwuke.dance.util.Util;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelbiz.WXOpenBusinessView;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author: 魏从响
 * @date: 2025/9/18
 */
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    private IWXAPI api;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, LPWHApplication.app_id, false);
        api.handleIntent(getIntent(), this);
    }

    @Override
    public void onReq(BaseReq baseReq) {
        // 微信向第三方应用发起请求会调用这个方法
    }

    @Override
    public void onResp(BaseResp baseResp) {
        // 第三方应用向微信发送请求后，微信返回结果会调用这个方法
        LogUtil.logD("获取微信类型", String.valueOf(baseResp.getType()));
        if (baseResp.getType() == 1) {
            SendAuth.Resp resp = (SendAuth.Resp) baseResp;
            if (resp.errCode == BaseResp.ErrCode.ERR_OK) {
                // 获取到code后，需要使用code去微信服务器换取access_token和openid
                String code = resp.code;

                // 这里需要调用微信的网络接口，通常是在服务器端完成这个步骤
                String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                        "appid=" + LPWHApplication.app_id +
                        "&secret=" + LPWHApplication.app_secret +
                        "&code=" + code +
                        "&grant_type=authorization_code";

                Map<String,String> map1 = new HashMap<>();
                PathUrl.withdraw(url, map1, new PathUrl.DataCallBack<WeChatCallbackBean>() {
                    @Override
                    public void onSucess(WeChatCallbackBean bean) {

                        if (Util.withdrawStart==1){
                            Util.withdrawStart = 0;
                            balanceWithdraw(bean.openid);//余额提现
                        }else if (Util.withdrawStart==2){
                            Util.withdrawStart = 0;
                            starlightValueWithdraw(bean.openid);//星光值提现
                        }
                    }

                    @Override
                    public void onFail(String errorCode) {
                        ToastUtil.setToast(WXEntryActivity.this,errorCode);
                    }
                });

            }

        }




    }

    /**
     * @description 余额提现
     * @param
     * @return
     * @author 魏从响
     * @time 2025/9/26 13:49
     */
    private void balanceWithdraw(String openid) {
        Random random = new Random();
        int randomInt = random.nextInt(1000000000)+1000000000;
        Map<String, Object> map = new HashMap<>();
        map.put("withdrawAccount","lantian_6434");//提现账号
        map.put("autonym","黄跃华");//提现实名
        map.put("amount",Util.withdrawAccount);//金额
        map.put("txnType","2");//类型
        map.put("txnSubType","2.1");//子类型
        map.put("userId", SharedPreferencesUtil.getInstance().getUserId());//用户ID
        map.put("password",Util.password);//支付密码
        map.put("orderId",randomInt);//订单号
        map.put("openid",openid);//openid  oJ9IT6QeEAUJ1jmMl0lTQokBnikc

        PathUrl.withdrawBalance(map, new PathUrl.DataCallBack<WXOpenBusinessViewBean>() {
            @Override
            public void onSucess(WXOpenBusinessViewBean bean) {
//                                ToastUtil.setToast(WXEntryActivity.this,"提现成功");
                Util.withdrawAccount = "";//金额
                Util.password = "";//支付密码
                int wxSdkVersion = api.getWXAppSupportAPI();
                //Build.OPEN_BUSINESS_VIEW_SDK_iNT
                if (wxSdkVersion >= 620889344) {
                    try {
                        String encodedValue1 = URLEncoder.encode(bean.mchId, "UTF-8");
                        String encodedValue2 = URLEncoder.encode(bean.appId, "UTF-8");
                        String encodedValue3 = URLEncoder.encode(bean.packageInfo, "UTF-8");
                        String q = "mchId="+encodedValue1+"&appId="+encodedValue2+"&package="+encodedValue3;
//                                        LogUtil.logD("消息:",q);
                        WXOpenBusinessView.Req req = new WXOpenBusinessView.Req();
                        req.businessType = "requestMerchantTransfer";
                        req.query = q;
                        Boolean ret = api.sendReq(req);
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    /*需提示用户升级微信版本*/
                    ToastUtil.setToast(WXEntryActivity.this,"微信版本过低，请升级微信版本");
                }

            }

            @Override
            public void onFail(String errorCode) {
                ToastUtil.setToast(WXEntryActivity.this,errorCode);
            }
        });
    }

    /**
     * @description 星光值提现
     * @param
     * @return
     * @author 魏从响
     * @time 2025/9/26 13:49
     */
    private void starlightValueWithdraw(String openid) {
        Random random = new Random();
        int randomInt = random.nextInt(1000000000)+1000000000;
        Map<String, Object> map = new HashMap<>();
        map.put("withdrawAccount","lantian_6434");//提现账号
        map.put("autonym","黄跃华");//提现实名
        map.put("amount",Util.withdrawAccount);//金额
        map.put("txnType","2");//类型
        map.put("txnSubType","2.1");//子类型
        map.put("userId", SharedPreferencesUtil.getInstance().getUserId());//用户ID
        map.put("password",Util.password);//支付密码
        map.put("orderId",randomInt);//订单号
        map.put("openid",openid);//openid  oJ9IT6QeEAUJ1jmMl0lTQokBnikc

        PathUrl.starlightValueTransferWithdraw(map, new PathUrl.DataCallBack<WXOpenBusinessViewBean>() {
            @Override
            public void onSucess(WXOpenBusinessViewBean bean) {
//                                ToastUtil.setToast(WXEntryActivity.this,"提现成功");
                Util.withdrawAccount = "";
                Util.password = "";
                int wxSdkVersion = api.getWXAppSupportAPI();
                //Build.OPEN_BUSINESS_VIEW_SDK_iNT
                if (wxSdkVersion >= 620889344) {
                    try {
                        String encodedValue1 = URLEncoder.encode(bean.mchId, "UTF-8");
                        String encodedValue2 = URLEncoder.encode(bean.appId, "UTF-8");
                        String encodedValue3 = URLEncoder.encode(bean.packageInfo, "UTF-8");
                        String q = "mchId="+encodedValue1+"&appId="+encodedValue2+"&package="+encodedValue3;
//                                        LogUtil.logD("消息:",q);
                        WXOpenBusinessView.Req req = new WXOpenBusinessView.Req();
                        req.businessType = "requestMerchantTransfer";
                        req.query = q;
                        Boolean ret = api.sendReq(req);
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    /*需提示用户升级微信版本*/
                    ToastUtil.setToast(WXEntryActivity.this,"微信版本过低，请升级微信版本");
                }

            }

            @Override
            public void onFail(String errorCode) {
                ToastUtil.setToast(WXEntryActivity.this,errorCode);
            }
        });

    }


}
